package com.study.multithreading.callable;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * @author HBZ
 * @description
 * @date 2021/5/12 16:59
 */
public class MyCallable implements Callable {
    /**
     * Computes a result, or throws an exception if unable to do so.
     *
     * @return computed result
     * @throws Exception if unable to compute a result
     */
    @Override
    public Object call() throws Exception {
        System.out.println(Thread.currentThread().getName() + "\t" + Thread.currentThread().getId() +  " \tstarting...");

        int sum = 0;
        for (int i = 0; i <= 100000; i++) {
            sum += i;
        }
        Thread.sleep(5000);

        System.out.println(Thread.currentThread().getName() + "\t" + Thread.currentThread().getId()  + " \tover...");
        return sum;
    }

    public static void main(String[] args) throws Exception {
        MyCallable myCallable=new MyCallable();
        FutureTask futureTask = new FutureTask<Integer>(myCallable);
        new Thread(futureTask).start();
        System.out.println("11");
        // get方法会阻塞调用的线程
        Integer sum = (Integer) futureTask.get();
        System.out.println("22");
        System.out.println(Thread.currentThread().getName() + Thread.currentThread().getId() + "=" + sum);
    }
}
